package com.newshub.admin.service.impl;

import com.newshub.admin.entity.RssFetchLog;
import com.newshub.admin.mapper.RssFetchLogMapper;
import com.newshub.admin.service.RssFetchLogService;
import com.newshub.business.dto.PageResult;
import com.newshub.logging.annotation.BusinessLog;
import com.newshub.logging.annotation.LogLevel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * RSS抓取日志服务实现类
 */
@Service
public class RssFetchLogServiceImpl implements RssFetchLogService {
    
    @Autowired
    private RssFetchLogMapper rssFetchLogMapper;
    
    @Override
    @BusinessLog(module = "抓取日志管理", description = "分页查询抓取日志", level = LogLevel.INFO)
    public PageResult<RssFetchLog> getPage(Long rssFeedId, String status, LocalDate startDate, 
                                         LocalDate endDate, int page, int size, String sortField, String sortOrder) {
        int offset = (page - 1) * size;
        List<RssFetchLog> list = rssFetchLogMapper.selectPage(rssFeedId, status, startDate, endDate, offset, size, sortField, sortOrder);
        long total = rssFetchLogMapper.count(rssFeedId, status, startDate, endDate);
        
        return PageResult.of(page, size, total, list);
    }
    
    @Override
    @BusinessLog(module = "抓取日志管理", description = "根据RSS源ID查询抓取日志", level = LogLevel.INFO)
    public PageResult<RssFetchLog> getByFeedId(Long rssFeedId, LocalDate startDate, 
                                             LocalDate endDate, int page, int size) {
        int offset = (page - 1) * size;
        List<RssFetchLog> list = rssFetchLogMapper.selectByFeedId(rssFeedId, startDate, endDate, offset, size);
        long total = rssFetchLogMapper.countByFeedId(rssFeedId, startDate, endDate);
        
        return PageResult.of(page, size, total, list);
    }
    
    @Override
    @BusinessLog(module = "抓取日志管理", description = "根据ID查询抓取日志", level = LogLevel.INFO)
    public RssFetchLog getById(Long id) {
        return rssFetchLogMapper.selectById(id);
    }
    
    @Override
    @BusinessLog(module = "抓取日志管理", description = "保存抓取日志", level = LogLevel.INFO)
    public void save(RssFetchLog log) {
        if (log.getId() == null) {
            rssFetchLogMapper.insert(log);
        } else {
            // 如果需要更新功能，可以添加update方法
            throw new UnsupportedOperationException("更新功能暂未实现");
        }
    }
    
    @Override
    @BusinessLog(module = "抓取日志管理", description = "删除抓取日志", level = LogLevel.WARN)
    public void deleteById(Long id) {
        rssFetchLogMapper.deleteById(id);
    }
    
    @Override
    @BusinessLog(module = "抓取日志管理", description = "批量删除抓取日志", level = LogLevel.WARN)
    public void deleteByIds(List<Long> ids) {
        if (ids != null && !ids.isEmpty()) {
            rssFetchLogMapper.deleteByIds(ids);
        }
    }
    
    @Override
    @BusinessLog(module = "抓取日志管理", description = "获取抓取统计信息", level = LogLevel.INFO)
    public Object getStatistics(Long rssFeedId, LocalDate startDate, LocalDate endDate) {
        // 这里可以实现统计功能，比如成功率、平均执行时间等
        // 暂时返回空Map，后续可以扩展
        Map<String, Object> statistics = new HashMap<>();
        statistics.put("totalCount", 0);
        statistics.put("successCount", 0);
        statistics.put("failedCount", 0);
        statistics.put("successRate", 0.0);
        statistics.put("avgExecutionTime", 0.0);
        return statistics;
    }
    
    @Override
    @BusinessLog(module = "抓取日志管理", description = "批量获取成功率统计", level = LogLevel.INFO)
    public Map<Long, Map<String, Object>> batchGetSuccessRates(List<Long> feedIds, int days) {
        if (feedIds == null || feedIds.isEmpty()) {
            return new HashMap<>();
        }
        
        // 计算日期范围
        LocalDate endDate = LocalDate.now();
        LocalDate startDate = endDate.minusDays(days - 1);
        
        // 批量查询所有相关抓取记录
        List<RssFetchLog> allLogs = rssFetchLogMapper.selectByFeedIdsAndDateRange(feedIds, startDate, endDate);
        
        // 使用Stream分组计算成功率
        Map<Long, Map<String, Object>> result = allLogs.stream()
            .collect(Collectors.groupingBy(
                RssFetchLog::getRssFeedId,
                Collectors.collectingAndThen(
                    Collectors.toList(),
                    logs -> calculateSuccessRateData(logs, days, startDate, endDate)
                )
            ));
        
        // 为没有抓取记录的RSS源添加默认数据
        for (Long feedId : feedIds) {
            if (!result.containsKey(feedId)) {
                result.put(feedId, createDefaultSuccessRateData(days, startDate, endDate));
            }
        }
        
        return result;
    }
    
    /**
     * 计算成功率数据
     */
    private Map<String, Object> calculateSuccessRateData(List<RssFetchLog> logs, int days, LocalDate startDate, LocalDate endDate) {
        int totalCount = logs.size();
        int successCount = (int) logs.stream().filter(this::isSuccessful).count();
        int effectiveSuccessCount = (int) logs.stream().filter(this::isEffectiveSuccessful).count();
        
        double successRate = totalCount > 0 ? ((double) successCount / totalCount) * 100 : 0.0;
        double effectiveSuccessRate = totalCount > 0 ? ((double) effectiveSuccessCount / totalCount) * 100 : 0.0;
        
        Map<String, Object> data = new HashMap<>();
        data.put("totalCount", totalCount);
        data.put("successCount", successCount);
        data.put("effectiveSuccessCount", effectiveSuccessCount);
        data.put("failedCount", totalCount - successCount);
        data.put("successRate", Math.round(successRate * 10.0) / 10.0);
        data.put("effectiveSuccessRate", Math.round(effectiveSuccessRate * 10.0) / 10.0);
        data.put("days", days);
        data.put("startDate", startDate);
        data.put("endDate", endDate);
        
        return data;
    }
    
    /**
     * 判断抓取是否成功（任务视图用）：基于日志status字段
     */
    private boolean isSuccessful(RssFetchLog log) {
        return log.getStatus() != null && "success".equalsIgnoreCase(log.getStatus());
    }
    
    /**
     * 判断抓取是否有效成功：status=success且totalFetched>0
     */
    private boolean isEffectiveSuccessful(RssFetchLog log) {
        return isSuccessful(log) && log.getTotalFetched() != null && log.getTotalFetched() > 0;
    }
    
    /**
     * 创建默认的成功率数据（无抓取记录时）
     */
    private Map<String, Object> createDefaultSuccessRateData(int days, LocalDate startDate, LocalDate endDate) {
        Map<String, Object> data = new HashMap<>();
        data.put("totalCount", 0);
        data.put("successCount", 0);
        data.put("effectiveSuccessCount", 0);
        data.put("failedCount", 0);
        data.put("successRate", 0.0);
        data.put("effectiveSuccessRate", 0.0);
        data.put("days", days);
        data.put("startDate", startDate);
        data.put("endDate", endDate);
        
        return data;
    }
}
